import os
from pathlib import Path
from typing import Optional

class DatabaseSchemaReader:
    """数据库结构文档读取工具"""
    
    def __init__(self, schema_file_path: Optional[str] = None):
        """
        初始化数据库结构文档读取工具
        
        Args:
            schema_file_path: 数据库结构文档路径
        """
        if schema_file_path is None:
            # 默认文档路径
            current_dir = Path(__file__).parent.parent.parent
            self.schema_file_path = current_dir / "docs" / "database_schema.md"
        else:
            self.schema_file_path = Path(schema_file_path)
    
    def read_schema_document(self) -> str:
        """
        读取数据库结构文档内容
        
        Returns:
            文档内容字符串
        """
        try:
            if not self.schema_file_path.exists():
                return f"错误: 数据库结构文档不存在，路径: {self.schema_file_path}"
            
            with open(self.schema_file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            return content
        except Exception as e:
            return f"读取数据库结构文档时出错: {str(e)}"
    
    def get_table_info(self, table_name: str) -> str:
        """
        获取特定表的信息
        
        Args:
            table_name: 表名
            
        Returns:
            表信息字符串
        """
        content = self.read_schema_document()
        lines = content.split('\n')
        
        # 查找表信息
        table_start = -1
        table_end = -1
        
        for i, line in enumerate(lines):
            if line.startswith(f"### {table_name}") or f"{table_name} 表结构" in line:
                table_start = i
                break
        
        if table_start == -1:
            return f"未找到表 '{table_name}' 的信息"
        
        # 查找表信息结束位置
        for i in range(table_start + 1, len(lines)):
            if lines[i].startswith("### ") or lines[i].startswith("## ") or i == len(lines) - 1:
                table_end = i
                break
        
        if table_end == -1:
            table_end = len(lines)
        
        return '\n'.join(lines[table_start:table_end])